package com.rslai.base.tool.servertest.database.dataset;

import com.rslai.base.tool.servertest.paramfilter.ParamFilter;

import java.util.ArrayList;
import java.util.List;

import org.dbunit.dataset.AbstractDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.ITableIterator;
import org.dbunit.dataset.ITableMetaData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ParamFilterDataSet extends AbstractDataSet {
    private final Logger logger = LoggerFactory.getLogger(ParamFilterDataSet.class);
    private IDataSet dataSet;
    private List<ParamFilter> valueReplacerList;

    public ParamFilterDataSet(IDataSet iDataSet, List<ParamFilter> valueReplacer) {
        this.dataSet = iDataSet;
        this.valueReplacerList = valueReplacer;
    }

    protected ITableIterator createIterator(boolean reversed) throws DataSetException {
        return new ReplacementIterator(this.dataSet.iterator());
    }

    private ParamFilterTable createReplacementTable(ITable table) {
        this.logger.debug("createReplacementTable(table={}) - start", table);
        return new ParamFilterTable(table, getValueReplacerList());
    }

    public synchronized List<ParamFilter> getValueReplacerList() {
        if (this.valueReplacerList == null) {
            this.valueReplacerList = new ArrayList();
        }
        return this.valueReplacerList;
    }

    private class ReplacementIterator implements ITableIterator {
        private final Logger logger = LoggerFactory.getLogger(ReplacementIterator.class);
        private final ITableIterator _iterator;

        public ReplacementIterator(ITableIterator iterator) {
            this._iterator = iterator;
        }

        public boolean next() throws DataSetException {
            this.logger.debug("next() - start");
            return this._iterator.next();
        }

        public ITableMetaData getTableMetaData() throws DataSetException {
            this.logger.debug("getTableMetaData() - start");
            return this._iterator.getTableMetaData();
        }

        public ITable getTable() throws DataSetException {
            this.logger.debug("getTable() - start");
            return ParamFilterDataSet.this.createReplacementTable(this._iterator.getTable());
        }
    }
}
